<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if (env('APP_DEBUG') == true) {
            DB::listen(function ($query) {
                $sql = $query->sql;

                if ($query->bindings) {
                    foreach ($query->bindings as $key => $value) {
                        $query->bindings[$key] = '"' . $value . '"';
                        $aRegex[]              = '/\?/';
                    }
                    $sql = preg_replace($aRegex, $query->bindings, $sql, 1);
                }

                Log::channel('daily')->info('execution time: ' . $query->time . 'ms; ' . $sql);
            });
        }
        Validator::extend('simple_validate_phone_number',function ($attribute, $value, $parameters) {
            return preg_match('/^(\+1 )?\d+$/', $value);
        });
        Validator::extend('phone_number',function ($attribute, $value, $parameters) {
            return preg_match('/^1[1-9][0-9]{9}$/', $value);
        });
        Validator::extend('discount_code',function ($attribute, $value, $parameters) {
            return preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,60}$/', $value);
        });
        Validator::extend('price',function ($attribute, $value, $parameters) {
            return preg_match('/^(?!0*[.,]0*$|[.,]0*$|0*$)[0-9]{1,8}(.[0-9]{1,2})?$/', $value);
        });
        Validator::extend('with_zero_price',function ($attribute, $value, $parameters) {
            return preg_match('/^[0-9]{1,8}(.[0-9]{1,2})?$/', $value);
        });
        Validator::extend('weight',function ($attribute, $value, $parameters) {
            return preg_match('/^$|null|^[0-9]{1,8}(.[0-9]{1,2})?$/', $value);
        });
        Validator::extend('shelves_code',function ($attribute, $value, $parameters) {
            return preg_match('/^[a-zA-Z]{1}\d{1,3}-\d{1,3}-\d{1,3}$/', $value);
        });
    }
}
